import 'dart:ffi';
import 'dart:ui';
import 'package:magic_car/util/config.dart';
import 'package:flutter/material.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:flutter/services.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

class BlancePage extends StatefulWidget {
  BlancePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<BlancePage> {
  Map acountinfo = new Map();

  String balance = "0.00";
  String chargemoney = "0.00";

  List moneylist = [
    {'value': '10', 'select': '0'},
    {'value': '30', 'select': '0'},
    {'value': '50', 'select': '0'},
    {'value': '100', 'select': '0'},
    {'value': '200', 'select': '0'},
  ];
  @override
  void initState() {
    super.initState();
    fluwx.weChatResponseEventHandler.listen((res) {
      print(res);
      if (res is fluwx.WeChatPaymentResponse) {
        if (res.isSuccessful) {
          //支付成功
          Toast.show('充值成功', context);
          loaddata();
        }
      }
    });
    loaddata(); //页面展示时加载数据
  }

  //加载数据
  loaddata() async {
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["id"] = pref.getString('uid');

    print(map);

    HttpHelper.post(HttpHelper.API_BusinessInfo, (data) async {
      if (data != null) {
        print(data);
        print(data["info"].length.toString());
        if (data["code"].toString() == "1") {
          setState(() {
            acountinfo = data["info"];
            balance = data["info"]["balance"];
          });
        }
      }
    }, params: map);
  }

  pay() async {
    Map<String, String> param = new Map();
    param['money'] = chargemoney;
    SharedPreferences pref = await SharedPreferences.getInstance();
    param["uid"] = pref.getString('uid');
    param["ctype"] = "1";
    HttpHelper.post(HttpHelper.API_Charger, (data) async {
      //loadpage.close();
      //loadpage.close();
      if (data != null) {
        if (data["code"].toString() == "1") {
          var payinfo = data['info'];
          print(payinfo['prepayid']['0']);
          fluwx.payWithWeChat(
              appId: Config.wx_appid,
              partnerId: payinfo['partnerid'],
              prepayId: payinfo['prepayid']['0'],
              packageValue: payinfo['package'],
              nonceStr: payinfo['noncestr'],
              timeStamp: int.parse(payinfo['timestamp']),
              sign: payinfo['sign']);
        } else {
          Toast.show(data['msg'], context);
        }
      }
    }, params: param);
  }

  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text('我的余额'),
          backgroundColor: Colors.white,
          elevation: 0,
        ),
        body: new Container(
          color: Color.fromRGBO(239, 239, 239, 1),
          child: new ListView(
            children: <Widget>[
              new Padding(
                padding: new EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 15.0),
                child: new Column(
                  children: <Widget>[
                    new Container(
                        color: Colors.white,
                        child: new Column(children: <Widget>[
                          new Padding(
                            padding:
                                new EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 10.0),
                            child: new Center(
                              child: new Text(
                                '可用余额',
                                style: TextStyle(fontSize: 15),
                              ),
                            ),
                          ),
                          new Padding(
                            padding:
                                new EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 30.0),
                            child: new Center(
                              child: new Text(
                                balance,
                                style: TextStyle(fontSize: 24),
                              ),
                            ),
                          ),
                          new Container(
                            height: 1,
                            color: Color.fromRGBO(239, 239, 239, 1),
                          ),
                          // new Padding(
                          //   padding:
                          //       new EdgeInsets.fromLTRB(0.0, 20.0, 0.0, 10.0),
                          //   child: new Center(
                          //     child: new Text(
                          //       '总收益',
                          //       style: TextStyle(fontSize: 15),
                          //     ),
                          //   ),
                          // ),
                          // new Padding(
                          //   padding:
                          //       new EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 30.0),
                          //   child: new Center(
                          //     child: new Text(
                          //       acountinfo.containsKey('total')?acountinfo["total"].toString():"0.00",
                          //       style: TextStyle(fontSize: 24,fontWeight: FontWeight.w400),
                          //     ),
                          //   ),
                          // )
                        ])),
                    new Padding(
                        padding: EdgeInsets.fromLTRB(20, 10, 20, 0),
                        child: Align(
                          alignment: Alignment.topLeft,
                          child: Text('立即充值(此充值不可退费)'),
                        )),
                    buildmoney(),
                    new Padding(
                        padding:
                            new EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 10.0),
                        child: new Container(
                          width: double.infinity,
                          height: 40,

                          child: new Material(
                            color: Color.fromRGBO(239, 239, 239, 1),
                            //INK可以实现装饰容器
                            child: new Ink(
                              //用ink圆角矩形
                              // color: Colors.red,
                              decoration: new BoxDecoration(
                                //背景
                                color: Color.fromRGBO(27, 182, 251, 1),
                                //设置四周圆角 角度
                                borderRadius:
                                    BorderRadius.all(Radius.circular(20.0)),
                                //设置四周边框
                                border: new Border.all(
                                    width: 1,
                                    color: Color.fromRGBO(27, 182, 251, 1)),
                              ),
                              child: new InkWell(
                                  //圆角设置,给水波纹也设置同样的圆角
                                  //如果这里不设置就会出现矩形的水波纹效果
                                  borderRadius: new BorderRadius.circular(15.0),

                                  //设置点击事件回调
                                  onTap: () {
                                    FocusScope.of(context)
                                        .requestFocus(FocusNode()); //隐藏键盘
                                    if (chargemoney[0] == "0") {
                                      Toast.show('请输入正确的金��', context);
                                    } else if (double.parse(chargemoney) < 1) {
                                      Toast.show('充值金额必须大于1', context);
                                    } else {
                                      pay();
                                    }
                                    //
                                  },
                                  child: Container(
                                    //设置 child 居中
                                    alignment: Alignment(0, 0),
                                    height: 40,
                                    width: double.infinity,
                                    //color: Color.fromRGBO(27, 182, 251, 1),
                                    child: Text(
                                      "充值",
                                      style: TextStyle(color: Colors.white),
                                    ),
                                  )),
                            ),
                          ),
                          // child: new RaisedButton(
                          //   child: new Text(
                          //     '提现',
                          //     style: TextStyle(fontSize: 16),
                          //   ),
                          //   textColor: Colors.white,
                          //   color: Color.fromRGBO(27, 182, 251, 1),
                          //   onPressed: () {},
                          // ),
                        )),
                    // new Padding(
                    //     padding:
                    //         new EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
                    //     child: new Container(
                    //       width: double.infinity,
                    //       height: 40,
                    //       child: new Material(
                    //         color: Color.fromRGBO(239, 239, 239, 1),
                    //         //INK可以实现装饰容器
                    //         child: new Ink(
                    //           //用ink圆角矩形

                    //           decoration: new BoxDecoration(
                    //             //背景
                    //             color: Colors.white,
                    //             //设置四周圆角 角度
                    //             borderRadius:
                    //                 BorderRadius.all(Radius.circular(20.0)),
                    //             //设置四周边框
                    //             border: new Border.all(
                    //                 width: 1,
                    //                 color: Color.fromRGBO(27, 182, 251, 1)),
                    //           ),
                    //           child: new InkWell(
                    //               //圆角设置,给水波纹也设置同样的圆角
                    //               //如果这里不设置就会出现矩形的水波纹效果
                    //               borderRadius: new BorderRadius.circular(15.0),

                    //               //设置点击事件回调
                    //               onTap: () {
                    //                 //moneydetail
                    //                 Navigator.pushNamed(context, "moneydetail");
                    //               },
                    //               child: Container(
                    //                 //设置 child 居中
                    //                 alignment: Alignment(0, 0),
                    //                 height: 40,
                    //                 width: double.infinity,
                    //                 //color: Color.fromRGBO(27, 182, 251, 1),
                    //                 child: Text(
                    //                   "余额明细",
                    //                   style: TextStyle(
                    //                       color:
                    //                           Color.fromRGBO(27, 182, 251, 1)),
                    //                 ),
                    //               )),
                    //         ),
                    //       ),
                    //       // child: new RaisedButton(
                    //       //   child: new Text(
                    //       //     '账户明细',
                    //       //     style: TextStyle(fontSize: 16),
                    //       //   ),
                    //       //   textColor: Colors.white,
                    //       //   color: Color.fromRGBO(27, 182, 251, 1),
                    //       //   onPressed: () {},
                    //       // ),
                    //     )),
                    // Padding(padding: new EdgeInsets.fromLTRB(20.0, 50.0, 20.0, 10.0),child: new Center(
                    //   child:Text("交易检测收益每月最多可提现三次，单次金额不能低于100元",style: new TextStyle(color: Color.fromRGBO(102, 102, 102, 1),fontSize: 12),)
                    // ),)
                  ],
                ),
              ),
            ],
          ),
        ));
  }

  Widget buildmoney() {
    List<Widget> tiles = [];

    Widget content;

    List items = moneylist;
    print(items);
    // print('图片数组长度'+items.isNotEmpty.toString());
    if (items.length > 0) {
      // tiles.add(new Container(
      //       padding: new EdgeInsets.fromLTRB(60, 0, 20, 0),)
      for (var i = 0; i < items.length + 1; i++) {
        //List temp1 = items[i] as List;
        tiles.add(new Container(
            width: 120,
            height: 50,
            // decoration: new BoxDecoration(
            //   color: Colors.blue,
            //   borderRadius: new BorderRadius.all(new Radius.circular(5.0)),
            // ),
            padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
            child: Padding(
                padding: new EdgeInsets.fromLTRB(20, 10, 20, 10),
                child: GestureDetector(
                    onTap: () {
                      FocusScope.of(context).requestFocus(FocusNode()); //隐藏键盘
                      items[i]["select"] = '1';
                      for (var j = 0; j < items.length; j++) {
                        if (i == j) {
                          items[j]['select'] = '1';
                          setState(() {
                            chargemoney = items[j]['value'];
                          });
                        } else {
                          items[j]['select'] = '0';
                        }
                      }
                      setState(() {
                        moneylist = items;
                      });
                    },
                    child: i == items.length
                        ? TextField(
                            inputFormatters: [
                                WhitelistingTextInputFormatter(
                                    RegExp("[0-9]")), //只允许输入字母
                              ],
                            keyboardType: TextInputType.number,
                            onChanged: (value) {
                              print(value);
                              setState(() {
                                chargemoney = value;
                              });
                            },
                            decoration: InputDecoration(
                              contentPadding: new EdgeInsets.all(4),
                              // contentPadding: const EdgeInsets.symmetric(vertical: 4.0),
                              hintText: '输入金额',
                              enabledBorder: OutlineInputBorder(
                                /*边角*/
                                borderRadius: BorderRadius.all(
                                  Radius.circular(5), //边角为5
                                ),
                                borderSide: BorderSide(
                                  color:
                                      Color.fromRGBO(27, 182, 251, 1), //边线颜色为白色
                                  width: 1, //边线宽度为2
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(
                                  color:
                                      Color.fromRGBO(27, 182, 251, 1), //边框颜色为白色
                                  width: 1, //宽度为5
                                ),
                                borderRadius: BorderRadius.all(
                                  Radius.circular(5), //边角为30
                                ),
                              ),
                            ))
                        : new Container(
                            height: 50,
                            decoration: new BoxDecoration(
                              // border: new Border.all(width: 2.0, color: Color.fromRGBO(27, 182, 251, 1)),
                              color: items[i]['select'] == "0"
                                  ? Color.fromRGBO(27, 182, 251, 1)
                                  : Colors.red,
                              borderRadius: new BorderRadius.all(
                                  new Radius.circular(5.0)),
                            ),
                            child: Center(
                              child: Text(
                                items[i]['value'],
                                style: TextStyle(color: Colors.white),
                              ),
                            ),
                            //  new Column(
                            //   children: <Widget>[
                            //     Center(
                            //       child: Text(items[i]['value']),
                            //     ),
                            //   ],
                          )))));
      }
    }
    content = new Wrap(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }
}
